package controllers

import (
	"dmsv/agent"
	"dmsv/models"
	"dmsv/msg"
	"dmsv/process"
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"net/http"
	"strings"
)

type ManagerController struct {
	BaseController
}

func (this *ManagerController) URLMapping() {
	this.Mapping("agentSignIn", this.AgentSign)
	this.Mapping("agentSignOut", this.AgentSignOut)
	this.Mapping("agentSignUpdate", this.AgentUpdate)
	this.Mapping("agentSetStatus", this.AgentSetStatus)
	this.Mapping("agentGetStatus", this.AgentGetStatus)
	this.Mapping("queueAdd", this.QueueAdd)
	this.Mapping("queueUpdate", this.QueueUpdate)
	this.Mapping("queueDel", this.QueueDel)
	this.Mapping("enterpriseReg", this.EnterpriseReg)
	this.Mapping("enterpriseUpdate", this.EnterpriseUpdate)
	this.Mapping("addNumber", this.AddNumber)
	this.Mapping("delNumber", this.DelNumber)
	this.Mapping("callInConfig", this.CallInConfig)
	this.Mapping("app/basic", this.AppBasicConfig)

}

// @Title 注册企业
// @Description 允许企业开展呼入和呼出业务
// @Description display
// @Param   param   body       controllers.EnterpriseRegParam     true   ""
// @Success 200     {object}   controllers.Code
// @router  /enterpriseReg [post]
func (this *ManagerController) EnterpriseReg() {

	logs.Debug("receive:%v", string(this.Ctx.Input.RequestBody))
	param := EnterpriseRegParam{GetKey: false}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}
	number := strings.ReplaceAll(param.Number, "-", "")

	_, err := process.AddNewEnterprice(param.AppId, param.NavAudio, number, param.Acd, param.GetKey)
	if err != nil {
		this.Data["json"] = NumberExist
		this.ServeJSON()
		return
	}

	if len(number) == 0 {
		process.AddNewQue(param.AppId, "default", "", "", param.Acd, 0)
		models.StoreQue(0, param.AppId, "default", "", "", param.Acd)
	}

	models.StoreNewCompany(param.AppId, param.NavAudio, number, param.Acd, param.GetKey)

	msg.SynMsgSend(string(this.Ctx.Input.RequestBody), msg.MSG_TYPE_COMPANY_ADD)

	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 企业绑定中继
// @Description 给一个企业分配中继号
// @Description display
// @Param   param   body       controllers.EnterpriseNumber     true   ""
// @Success 200     {object}   controllers.Code
// @router  /addNumber [post]
func (this *ManagerController) AddNumber() {

	logs.Debug("receive:%v", string(this.Ctx.Input.RequestBody))
	param := EnterpriseNumber{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	if len(param.Number) == 0 {
		this.Data["json"] = NumberError
		this.ServeJSON()
		return
	}

	number := strings.ReplaceAll(param.Number, "-", "")
	err := process.EnterpriceAddNumber(param.AppId, number, param.Display)
	if err != nil {
		this.Data["json"] = QueRegFail
		this.ServeJSON()
		return
	}

	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 解绑企业中继
// @Description 解绑企业中继号
// @Description display
// @Param   param   body       controllers.EnterpriseNumber     true   ""
// @Success 200     {object}   controllers.Code
// @router  /delNumber [post]
func (this *ManagerController) DelNumber() {

	logs.Debug("receive:%v", string(this.Ctx.Input.RequestBody))
	param := EnterpriseNumber{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	if len(param.Number) == 0 {
		this.Data["json"] = NumberError
		this.ServeJSON()
		return
	}

	number := strings.ReplaceAll(param.Number, "-", "")
	err := process.EnterpriceDelNumber(param.AppId, number, param.Display)
	if err != nil {
		this.Data["json"] = QueRegFail
		this.ServeJSON()
		return
	}

	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 配置号码呼入
// @Description 配置号码呼入
// @Description display
// @Param   param   body       controllers.CallInConfig     true   ""
// @Success 200     {object}   controllers.Code
// @router  /callInConfig [post]
func (this *ManagerController) CallInConfig() {

	logs.Debug("receive call in config:%v", string(this.Ctx.Input.RequestBody))
	param := CallInConfig{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	number := strings.ReplaceAll(param.Number, "-", "")
	err := process.EnterpriceConfigCallIn(param.AppId, number, param.TransferType, param.Info)
	if err != nil {
		this.Data["json"] = QueRegFail
		this.ServeJSON()
		return
	}

	models.InsertNewCallInConf(number, param.TransferType, param.Info)

	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 注册企业
// @Description 允许企业开展呼入和呼出业务
// @Description display
// @Param   param   body       controllers.EnterpriseRegParam     true   ""
// @Success 200     {object}   controllers.Code
// @router  /enterpriseUpdate [post]
func (this *ManagerController) EnterpriseUpdate() {

	param := EnterpriseRegParam{GetKey: false}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &param); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	number := strings.ReplaceAll(param.Number, "-", "")
	err := process.EnterpriceUpdate(param.AppId, param.NavAudio, param.Acd, number)
	if err != nil {
		this.Data["json"] = QueRegFail
		this.ServeJSON()
		return
	}

	//同步到其他服务
	msg.SynMsgSend(string(this.Ctx.Input.RequestBody), msg.MSG_TYPE_COMPANY_UPDATE)

	models.UpdateCompany(param.AppId, param.NavAudio, number, param.Acd, param.GetKey)
	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 坐席状态查询
// @Description 签入情况下，设置坐席状态，未签入，设置无效；仅支持free、busy两种状态
// @Param   param   body       controllers.ServiceStatus     true   ""
// @Success 200     {object}   controllers.Code
// @router  /agentGetStatus [post]
func (this *ManagerController) AgentGetStatus() {

	params := ServiceStatus{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &params); err != nil {
		logs.Error("sign in err:%v,args:%v", err, string(this.Ctx.Input.RequestBody))
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	if len(params.ServiceId) < 4 {
		logs.Error("sign in err:%v. 坐席Id 太短.", string(this.Ctx.Input.RequestBody))
		this.Data["json"] = ServiceIdTooShort
		this.ServeJSON()
		return
	}

	status, err := process.ServiceGetStatus(params.AppId, params.ServiceId)
	if err != nil {
		logs.Error("获取状态错误 :%v,args:%v", err, string(this.Ctx.Input.RequestBody))
		this.Data["json"] = MakeSysErrCode(err.Error())
		this.ServeJSON()
		return
	}

	this.Data["json"] = MakeResp(Success, status)
	this.ServeJSON()
	return
}

// @Title 坐席状态设置
// @Description 签入情况下，设置坐席状态，未签入，设置无效；仅支持free、busy两种状态
// @Param   param   body       controllers.ServiceStatus     true   ""
// @Success 200     {object}   controllers.Code
// @router  /agentSetStatus [post]
func (this *ManagerController) AgentSetStatus() {

	params := ServiceStatus{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &params); err != nil {
		logs.Error("sign in err:%v,args:%v", err, string(this.Ctx.Input.RequestBody))
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	if len(params.ServiceId) < 4 {
		logs.Error("sign in err:%v. 坐席Id 太短.", string(this.Ctx.Input.RequestBody))
		this.Data["json"] = ServiceIdTooShort
		this.ServeJSON()
		return
	}

	err := process.ServiceSetStatus(params.AppId, params.ServiceId, params.Status)
	if err != nil {
		logs.Error("设置状态错误 :%v,args:%v,param:%v", err, string(this.Ctx.Input.RequestBody), params)
		this.Data["json"] = MakeSysErrCode(err.Error())
		this.ServeJSON()
		return
	}

	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 坐席签入
// @Description 坐席签入，display填外呼时显示的号码，在400的业务场景里，可以为空，使用公司绑定的号码外呼
// @Param   param   body       controllers.SignParam     true   "坐席相关信息,skillname:不填，则不签入队列，填default,签入默认队列"
// @Success 200     {object}   controllers.Code
// @router  /agentSignIn [post]
func (this *ManagerController) AgentSign() {

	params := SignParam{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &params); err != nil {
		logs.Error("sign in err:%v,args:%v", err, string(this.Ctx.Input.RequestBody))
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	if len(params.ServiceId) < 4 {
		logs.Error("sign in err:%v. 坐席Id 太短.", string(this.Ctx.Input.RequestBody))
		this.Data["json"] = ServiceIdTooShort
		this.ServeJSON()
		return
	}
	/*
		_, err := strconv.ParseFloat(params.ServiceId, 64)
		if err != nil {
			this.Data["json"] = ServiceIdError
			this.ServeJSON()
			return
		}*/

	number := strings.ReplaceAll(params.Number, "-", "")
	if len(params.SkillId) == 0 {
		params.SkillId = "default"
	}

	//坐席签入到队列
	err := process.ServiceSignIn(params.AppId, params.SkillId, number, params.ServiceId, params.Display)
	if err != nil {
		logs.Error("sign in err:%v,args:%v", err, params)
		this.Data["json"] = makeCode(http.StatusFailedDependency, 600001, err.Error())
		this.ServeJSON()
		return
	}

	//同步到其他服务
	msg.SynMsgSend(string(this.Ctx.Input.RequestBody), msg.MSG_TYPE_AGENT_SIGN_IN)

	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 坐席签出
// @Description 坐席签出，签出指定队列，或者全部签出
// @Param   param   body       controllers.SignParam     true   "坐席相关信息,skillname:不填，则签出所有队列,否则签出指定队列"
// @Success 200     {object}   controllers.Code
// @router  /agentSignOut [post]
func (this *ManagerController) AgentSignOut() {

	params := SignParam{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &params); err != nil {
		logs.Error("sign out err:%v,args:%v", err, string(this.Ctx.Input.RequestBody))
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	logs.Debug("坐席签出:%v", string(this.Ctx.Input.RequestBody))

	//坐席签出到队列
	err := process.ServiceSignOut(params.AppId, params.SkillId, params.ServiceId)
	if err != nil {
		logs.Warn("签出失败:%v", err.Error())
	}

	//同步到其他服务
	msg.SynMsgSend(string(this.Ctx.Input.RequestBody), msg.MSG_TYPE_AGENT_SIGN_OFF)

	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 修改坐席信息
// @Description 修改坐席信息
// @Param   param   body       controllers.SignParam     true   "修改坐席的接听信息"
// @Success 200     {object}   controllers.Code
// @router  /agentSignUpdate [post]
func (this *ManagerController) AgentUpdate() {

	params := SignParam{}
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &params); err != nil {
		logs.Error("sign out err:%v,args:%v", err, string(this.Ctx.Input.RequestBody))
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	appId := fmt.Sprintf("%d", params.AppId)
	agent.UpdateAgentAnswerNumber(appId, params.ServiceId, params.Number)

	this.Data["json"] = Success
	this.ServeJSON()
	return
}

// @Title 添加队列
// @Description
// @Param   param   body   controllers.QueParam     true   "队列相关信息"
// @Success 200 {object}   controllers.Code
// @Failure 400
// @Failure 404
// @router /queueAdd [post]
func (this *ManagerController) QueueAdd() {

	params := QueParam{}
	logs.Info("add new queue: %v", string(this.Ctx.Input.RequestBody))
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &params); err != nil {
		logs.Error("add new queue fail:%v", err)
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	res := process.AddNewQue(params.AppId, params.Name, params.Key, params.Media, params.Distrb, params.Id)
	if res {

		//同步
		msg.SynMsgSend(string(this.Ctx.Input.RequestBody), msg.MSG_TYPE_QUEUE_ADD)

		err := models.StoreQue(params.Id, params.AppId, params.Name, params.Key, params.Media, params.Distrb)
		if err != nil {
			logs.Debug("store que:%v", err)
		}

		this.Data["json"] = Success
	} else {
		logs.Info("add new queue: %v for company :%v failed", params.Name, params.AppId)
		this.Data["json"] = QueRegFail
	}

	this.ServeJSON()
	return
}

// @Title 修改队列
// @Description
// @Param   param   body   controllers.QueParam     true   "队列相关信息"
// @Success 200 {object}   controllers.Code
// @Failure 400
// @Failure 404
// @router /queueUpdate [post]
func (this *ManagerController) QueueUpdate() {
	params := QueParam{}
	logs.Info("update queue: %v", string(this.Ctx.Input.RequestBody))
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &params); err != nil {
		logs.Debug("json failed:%v", err)
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	res := process.UpdateQue(params.AppId, params.Name, params.Key, params.Media, params.Distrb, params.Id)
	if res {
		//同步
		msg.SynMsgSend(string(this.Ctx.Input.RequestBody), msg.MSG_TYPE_QUEUE_UPDATE)

		models.UpdateQue(params.Id, params.Name, params.Key, params.Media, params.Distrb)
		this.Data["json"] = Success
	} else {
		this.Data["json"] = QueRegFail
	}

	this.ServeJSON()
	return
}

// @Title 删除队列
// @Description 删除企业的指定队列
// @Param   param   body   controllers.QueParam     true   "企业Id,name 为必选，其他不需要"
// @Success 200 {object}   controllers.Code
// @Failure 400
// @Failure 404
// @router /queueDel [post]
func (this *ManagerController) QueueDel() {

	params := QueParam{}
	logs.Info("del queue: %v", string(this.Ctx.Input.RequestBody))
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &params); err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	res := process.DelQue(params.AppId, params.Name)
	if res {

		//同步
		msg.SynMsgSend(string(this.Ctx.Input.RequestBody), msg.MSG_TYPE_QUEUE_DEL)

		this.Data["json"] = Success
		models.DelQue(params.Id, params.AppId, params.Name)
	} else {
		this.Data["json"] = QueRegFail
	}

	this.ServeJSON()
	return
}

// @Title 基础配置
// @Description
// @Param   param   body   map[string]interface     true   ""
// @Success 200 {object}   controllers.Code
// @Failure 400
// @Failure 404
// @router /app/basic [post]
func (this *ManagerController) AppBasicConfig() {

	params := make(map[string]interface{})
	logs.Info("修改基础参数:[%v]", string(this.Ctx.Input.RequestBody))
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &params)
	if err != nil {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	appId, ok := params["appId"]
	if !ok {
		this.Data["json"] = ParamsError
		this.ServeJSON()
		return
	}

	if v, yes := params["arrange"]; yes {
		err = process.SetCompanyBasic(appId.(string), process.BASIC_TYPE_ARRANGE, v)
		if err != nil {
			this.Data["json"] = AppIdNotExist
			this.ServeJSON()
			return
		}
	}

	if v, yes := params["arrangeTime"]; yes {
		err = process.SetCompanyBasic(appId.(string), process.BASIC_TYPE_ARRANGE_T, v)
		if err != nil {
			this.Data["json"] = AppIdNotExist
			this.ServeJSON()
			return
		}
	}

	if v, yes := params["bindModel"]; yes {
		err = process.SetCompanyBasic(appId.(string), process.BASIC_TYPE_BIND_MODEL, v)
		if err != nil {
			this.Data["json"] = AppIdNotExist
			this.ServeJSON()
			return
		}
	}

	if v, yes := params["autoAnswer"]; yes {
		err = process.SetCompanyBasic(appId.(string), process.BASIC_TYPE_AUTO_ANSWER, v)
		if err != nil {
			this.Data["json"] = AppIdNotExist
			this.ServeJSON()
			return
		}
	}

	if v, yes := params["errPass"]; yes {
		err = process.SetCompanyBasic(appId.(string), process.BASIC_TYPE_MIS_CALL, v)
		if err != nil {
			this.Data["json"] = AppIdNotExist
			this.ServeJSON()
			return
		}
	}

	if v, yes := params["errNumber"]; yes {
		err = process.SetCompanyBasic(appId.(string), process.BASIC_TYPE_MIS_NUMBER, v)
		if err != nil {
			this.Data["json"] = AppIdNotExist
			this.ServeJSON()
			return
		}
	}

	this.Data["json"] = Success
	this.ServeJSON()
	return

}
